/*
 * @Author: gk
 * @Date:   2019-01-21 14:57:47
 * @Last Modified by:   gk
 * @Last Modified time: 2019-03-27 15:44:21
 */

function PublicFunction() {};

/**
 * 
 * 时间
 * 
 */

Date.prototype.format = function(format) { //给时间添加一个处理时间格式的函数  new Date().format("MM-dd");new Date().format("MM/dd");
	var date = {
		"M+": this.getMonth() + 1,
		"d+": this.getDate(),
		"h+": this.getHours(),
		"m+": this.getMinutes(),
		"s+": this.getSeconds(),
		"q+": Math.floor((this.getMonth() + 3) / 3),
		"S+": this.getMilliseconds()
	};
	if(/(y+)/i.test(format)) {
		format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
	}
	for(var k in date) {
		if(new RegExp("(" + k + ")").test(format)) {
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? date[k] : ("00" + date[k]).substr(("" + date[k]).length))
		}
	}
	return format
};

PublicFunction.prototype.getNowFormatDateAfter = function(AddDayCount, date) { //获取AddDayCount天后的日期getNowFormatDateAfter(2019-04-03,2)=>2019-04-05
	var oDate = date ? this.getTimeFormat(date) : new Date();
	oDate.setDate(oDate.getDate() + AddDayCount);
	return oDate;
};

PublicFunction.prototype.getTimeFormat = function(date) { //兼容ios的时间格式处理
	var oDate = date.replace(/-/g, '/').replace(/\./g, '/');
	oDate = new Date(oDate);
	return oDate;
};

PublicFunction.prototype.getTime = function(date) { //处理时间   getTime(new Date())
	var oDate = date ? this.getTimeFormat(date) : new Date();
	var y = oDate.getFullYear();
	var m = oDate.getMonth() + 1;
	var d = oDate.getDate();
	var h = oDate.getHours();
	var min = oDate.getMinutes();
	var s = oDate.getSeconds();
	return {
		y: y,
		m: m,
		d: d,
		h: h,
		min: min,
		s: s
	}
};

PublicFunction.prototype.getWeek = function(departureDate) { //获取周几并判断是否为今天     用法getWeek(2019-04-03)
	var day = departureDate ? this.getTimeFormat(departureDate) : new Date(); //将日期值格式化
	departureDate = day.format('yyyy-MM-dd');
	var today = new Date().format('yyyy-MM-dd');
	var weekday = new Array("周日", "周一", "周二", "周三", "周四", "周五", "周六"); //创建星期数组
	var tomorrow = this.getNowFormatDateAfter(1).format('yyyy-MM-dd'); //获取明天的日期
	var dopodomani = this.getNowFormatDateAfter(2).format('yyyy-MM-dd'); //获取后天的日期
	var yesterday = this.getNowFormatDateAfter(-1).format('yyyy-MM-dd'); //获取昨天的日期
	var beforeYesterday = this.getNowFormatDateAfter(-2).format('yyyy-MM-dd'); //获取前天的日期
	var obj = {};
	obj.isToday = (departureDate == today); //是否为今天
	obj.isTomorrow = (departureDate == tomorrow); //是否为明天
	obj.isDopodomani = (departureDate == dopodomani); //是否为后天
	obj.isYesterday = (departureDate == yesterday); //是否为昨天
	obj.isBeforeYesterday = (departureDate == beforeYesterday); //是否为前天
	obj.week = weekday[day.getDay()];//周几
	obj.day = day.format('MM-dd');//月日
	obj.time = day.format('hh:mm');//时分
	return obj;
};

PublicFunction.prototype.isDateBetween = function(dateString, startDateString, endDateString) { //判断日期是否在设定区间内 isDateBetween(2019-04-03,2019-04-01,2019-04-05)=>true
	//参数 判断时间 开始时间 结束时间
	var flag = false;
	var startFlag = (this.dateCompare(dateString, startDateString) < 1);
	var endFlag = (this.dateCompare(dateString, endDateString) > -1);
	(startFlag && endFlag) && (flag = true);
	return flag
};

PublicFunction.prototype.dateCompare = function(dateString, compareDateString) { //判断日期的先后关系
	//结果 0为相同 1为后者大 -1为前者大
	var dateTime = this.getTimeFormat(dateString).getTime();
	var compareDateTime = this.getTimeFormat(compareDateString).getTime();
	var flag = 0;
	(compareDateTime > dateTime) && (flag = 1);
	(compareDateTime < dateTime) && (flag = -1);
	return flag;
};

PublicFunction.prototype.dateNum = function(y,m,d) { //获取该天是这一年的第几天 传入年，月，日 
	var dataOne = y + ".01.01";
	var dataTwo = y + "." + m + "." + d;
	var numOne = new Date(dataOne).getTime();
	var numTwo = new Date(dataTwo).getTime();
	day = (numTwo - numOne) / (1000*60*60*24);
	return day + 1;
};

/**
 * 
 * 设备信息
 * 
 */

PublicFunction.prototype.IsMove = function() { //获取设备信息安卓还是ios 
	var u = navigator.userAgent,
		app = navigator.appVersion;
	var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;
	var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
	return {
		isAndroid: isAndroid,
		isiOS: isiOS,
	};
};

PublicFunction.prototype.IsPC = function() { //pc还是移动
	var userAgentInfo = navigator.userAgent;
	var Agents = ["Android", "iPhone",
		"SymbianOS", "Windows Phone",
		"iPad", "iPod"
	];
	var flag = true;
	for(var v = 0; v < Agents.length; v++) {
		if(userAgentInfo.indexOf(Agents[v]) > 0) {
			flag = false;
			break;
		}
	}
	return flag;
};

PublicFunction.prototype.getFacilityMgs = function() { //获取设备信息
	var isMove = this.IsMove();
	return {
		isPC: this.IsPC(),
		isAndroid: isMove.isAndroid,
		isiOS: isMove.isiOS,
	};
};

/**
 *
 * 正则
 * 
 */

PublicFunction.prototype.checkPhoneNum = function(val) { //手机号验证
	return /^1\d{10}$/.test(val);
};

PublicFunction.prototype.checkIDNum = function(val) { //身份证号验证
	return /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/.test(val);
};

PublicFunction.prototype.checkEmail = function(val) { //邮箱验证
	return /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/.test(val);
};

/**
 *
 * 数字
 * 
 */

PublicFunction.prototype.getRandom = function(a, b) { //获取任意范围内的随机整数
	return ~~(Math.random() * (b - a) + a);
};

PublicFunction.prototype.zeroFill = function(s) { //数字补0
	return s < 10 ? '0' + s : s
};

/**
 *
 *  页面参数
 * 
 */

PublicFunction.prototype.getPageString = function(name) { //获取页面相应参数
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if(r != null) {
		return unescape(r[2])
	}
	return ''
};

PublicFunction.prototype.getPageAllString = function() { //获取页面所有参数
	var mgs = {}; //参数结果
	var url = window.location.href; //获取路径得到传参
	var a = url.indexOf("?"); //根据问号得到传参的位置
	if(a > -1) {
		var b = url.substr(a + 1); //拿到参数的字符串
		var mgsArr = b.split("&"); //改写为一个数组
		mgsArr.forEach(function(val) { //遍历
			var arr = val.split("=");
			mgs[arr[0]] = arr[1];
		});
	};
	return mgs;
};

/**
 *
 *  其他
 * 
 */

PublicFunction.prototype.copyText = function(text) { //复制文字（该方法无法在异步环境使用 document.execCommand不支持）
	var input = document.createElement("input");   
	input.setAttribute("readonly", true); //设置只读防止ios唤起键盘
	input.value = text;   //copy的文字  
	document.body.appendChild(input);      
	input.select();      
	input.setSelectionRange(0, input.value.length), document.execCommand('Copy');      
	document.body.removeChild(input);
};

PublicFunction.prototype.idCardFilter = function(num) { //身份证手机号等加密--大于16位的必须传字符串
	(typeof num == "String") || (num = String(num));
	var length = num.length;
	var str = "";
	for(var i = 0; i < length - 7; i++) {
		str += "*"
	};
	return num.substring(0, 3) + str + num.substring(num.length - 4, num.length);
};

PublicFunction.prototype.getIDNumber = function(str) { //输入前17位计算第18位返回身份证号
	var arr = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; //系数
	var lastNumArr = [1, 0, "X", 9, 8, 7, 6, 5, 4, 3, 2]; //对应数
	var numArr = str.split("");
	var allNum = 0;
	arr.forEach((val, key) => {
		allNum += val * numArr[key];
	});
	var lastNum = lastNumArr[allNum % 11];
	str.length = 17;
	var result = str + lastNum;
	return result
};

PublicFunction.prototype.preventContinuousClicked = function(that, second) { //防止连点
	//(传入this,记录时间),连点的时间间隔默认为500毫秒
	var nowTime = (new Date()).getTime();
	second || (second = 500);
	var flag = true; //true为可以点击 false为触发连点
	if(that.preventContinuousClickedTime) {
		flag = (nowTime - that.preventContinuousClickedTime) > second;
	} else {
		that.preventContinuousClickedTime = nowTime;
		var time = setTimeout(function() {
			that.preventContinuousClickedTime = null;
			clearTimeout(time); //清除延时器释放内存
		}, second);
	}
	return flag;
};

PublicFunction.prototype.countDown = function(second, that, fn) { //倒计时 （锁屏依然有效） 
	/**
	 * 1.second 传入剩余倒计时秒数
	 *
	 * 2.that (出入this,this仅为数据的存储位置，如小程序开发传入 this.data vue传入this)
	 *
	 * 3.fn 读秒结束的回调函数
	 *
	 *  将会给this上挂载一个所剩读秒的对象 名为 _countDownTime 包含分秒俩个值
	 *  that._countDownTime = {
	 *  	min:"", //分
	 *  	s:"" //秒
	 *  };
	 */
	var lastTime = (new Date()).getTime(); //记录上次的时间初始值为开始
	var residueTime = second; //记录剩余的秒数
	that._countDownTime || (that._countDownTime = {});
	var timer = setInterval(function() {
		var nowTime = (new Date()).getTime(); //获取现在的时间
		//计算时间差
		var time = (nowTime - lastTime) / 1000; //取整
		residueTime = residueTime - time; //获得剩余的秒数
		lastTime = nowTime; //更新上一个时间
		if(residueTime > 0) { //剩余的秒数转化格式
			if(that._countDownTime) {
				that._countDownTime.min = Math.floor(residueTime / 60);
				that._countDownTime.s = (residueTime % 60).toFixed(0);
				//格式化时间
				that._countDownTime.min = Number(that._countDownTime.min);
				that._countDownTime.min = (that._countDownTime.min > 9) ? that._countDownTime.min : "0" + that._countDownTime.min;
				that._countDownTime.s = (that._countDownTime.s > 9) ? that._countDownTime.s : "0" + that._countDownTime.s;
			}
		} else { //归0时
			clearInterval(timer); //清除定时器
			if(that._countDownTime) {
				that._countDownTime.min = 0;
				that._countDownTime.s = 0;
			};
			fn && fn();
		};
	}, 1000);
	return timer; //返回定时器可以在不需要的时候强制终止倒计时
};


/*********封装简易watch监听器微信小程序**********/
/**
 * 使用方法
 * 对应js引入文件  例如 var publicMethod = require("../../commentjs/public.js");
 * 在onLoad中加入如下代码激活监听器 publicMethod.setWatcher(this);
 */

PublicFunction.prototype.setWatcher = function(that) {//设置监听器 
  // 接收传过来的this对象
  Object.keys(that.watch).forEach(i => { // 将watch对象内的key遍历
    this.observe(i, that); // 监听data内的i属性，传入watch内对应函数以调用
  })
};

PublicFunction.prototype.observe = function(key, that) {//监听属性 并执行监听函数
  var val = that.data[key]; // 给该属性设默认值
  Object.defineProperty(that.data, key, {
    configurable: true,
    enumerable: true,
    set: function (value) {
      //函数接收改监听变量当前的值
      that.watch[key].call(that, value); // 赋值(set)时，调用对应函数并且修改this指针
    },
    get: function () {
      return val;
    }
  })
};

var publicMethod = new PublicFunction();